package com.jiayu.seckilldemo.rabbitmq;

import com.jiayu.seckilldemo.pojo.SeckillOrder;
import com.jiayu.seckilldemo.pojo.User;
import com.jiayu.seckilldemo.service.IGoodsService;
import com.jiayu.seckilldemo.service.IOrderService;
import com.jiayu.seckilldemo.utils.JsonUtil;
import com.jiayu.seckilldemo.vo.GoodsVo;
import com.jiayu.seckilldemo.vo.SeckillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

/**
 * @author ：jiayu
 * @description：消息消费者
 * @date ：2022/7/28 11:04
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("接收消息：" + message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        //判断是否重复抢购
        String seckillOrderJson  = (String) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if(!StringUtils.isEmpty(seckillOrderJson)){
            return;
        }
        //下单操作
        orderService.seckill(user, goodsVo);

    }




//    //配置是哪个队列来监听消息
//    @RabbitListener(queues = "queue")
//    public void receive(Object message){
//        log.info("接收消息："+ message);
//    }
//
//
//    @RabbitListener(queues = "queue_fanout01")
//    public void receive01(Object message){
//        log.info("QUEUE01接收消息："+ message);
//    }
//
//    @RabbitListener(queues = "queue_fanout02")
//    public void receive02(Object message){
//        log.info("QUEUE02接收消息："+ message);
//    }
//
//
//    @RabbitListener(queues = "queue_direct01")
//    public void receive03(Object message){
//        log.info("QUEUE01接收消息："+ message);
//    }
//
//    @RabbitListener(queues = "queue_topic01")
//    public void receive05(Object message){
//        log.info("QUEUE01接收消息："+ message);
//    }
//
//    @RabbitListener(queues = "queue_topic02")
//    public void receive06(Object message){
//        log.info("QUEUE02接收消息："+ message);
//    }





}
